package com.ccplay.dataservice.web;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ccplay.dataservice.dto.FileUploadResult;
import com.google.gson.reflect.TypeToken;
import com.oxygen.components.ServletUploadFileItem;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.dto.UserDto;
import com.oxygen.enums.ApiMethodEnum;
import com.oxygen.enums.ApiMsgEnum;
import com.oxygen.util.DateTimeUtil;
import com.oxygen.util.JsonUtil;

@Controller
public class FileUploadAction extends BaseAction {

	/**
	 * 上传头像、封面
	 * 
	 * @param req
	 * @param rsp
	 * @return
	 * @throws Exception
	 * @author Daniel
	 */
	@RequestMapping(value = { "/upload", "/upload/" }, method = RequestMethod.POST)
	public String updateIconProfile(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			ServletUploadFileItem servletUploadFileItem = this.getUploadFileItem(req, fileUploadImageMaxSize);
			List<FileItem> fileList = servletUploadFileItem.getFileItem();
			Map<String, Object> paramMap = servletUploadFileItem.getFormFieldItems();
			String bizFlag = null;
			if (paramMap != null && paramMap.containsKey("biz_flag")) {
				bizFlag = paramMap.get("biz_flag").toString();
			}
			FileItem fileItem = null;
			if (fileList != null) {
				fileItem = fileList.get(0);
			}
			if (fileItem == null) {
				return this.outputApiFinalResponse(null, ApiMsgEnum.FileItemException, rsp);
			}
			if ("user_icon".equals(bizFlag)) {
				return this.uploadAndUpdateUserIconOrCover(req, rsp, fileItem, paramMap, "icon");
			} else if ("user_cover".equals(bizFlag)) {
				return this.uploadAndUpdateUserIconOrCover(req, rsp, fileItem, paramMap, "cover");
			} else {
				return this.outputApiFinalResponse(null, ApiMsgEnum.ForbiddenException, rsp);
			}
		} catch (FileSizeLimitExceededException e) {
			return this.outputApiFinalResponse(null, ApiMsgEnum.FileSizeException, rsp);
		} catch (Exception e) {
			return this.outputApiFinalResponse(null, ApiMsgEnum.FileUploadException, rsp);
		}
	}

	/**
	 * 上传并修改用户头像或者封面
	 * 
	 * @param req
	 * @param rsp
	 * @return
	 * @throws Exception
	 * @author Daniel
	 */
	private String uploadAndUpdateUserIconOrCover(HttpServletRequest req, HttpServletResponse rsp, FileItem fileItem, Map<String, Object> paramMap, String iconOrCover) throws Exception {
		UserDto userDto = this.getSimpleProfile(req, paramMap);
		if (userDto != null) {
			// Date signupDate =
			// DateTimeUtil.parseDateTime(userDto.getSignup_date(),
			// DateTimeUtil.DATETIME_PATTERN_LONG);
			// if (signupDate == null) {
			// signupDate = new Date();
			// }
			String timeStr = DateTimeUtil.formatDateTime(new Date(), "yyyy/MM/dd/HHmm-ss-SSS");
			String fileDir = fileUploadUserDirName + File.separator + timeStr + File.separator;
			// 上传图片并提交到CDN
			FileUploadResult uploadResult = this.uploadImage(fileItem, fileDir);
			if (uploadResult.getIsSuccess() == Boolean.TRUE && uploadResult.getFileDto() != null) {
				// 更新数据库
				paramMap.put(iconOrCover, uploadResult.getFileDto().getPath().replaceFirst(MEDIA_PREFIX, ""));
				String retJson = this.callApi(ApiMethodEnum.USER_UPDATEPROFILE, paramMap);
				return this.outputJson(retJson, rsp);
			} else {
				// retMsg = uploadResult.getMsg();
			}
		}
		return this.outputApiFinalResponse(ApiMethodEnum.USER_UPDATEPROFILE.getCode(), ApiMsgEnum.BadRequestException, rsp);
	}

	private UserDto getSimpleProfile(HttpServletRequest req, Map<String, Object> paramMap) {
		UserDto userDto = null;
		String json = this.callApi(ApiMethodEnum.USER_GETSIMPLEPROFILE, paramMap);
		if (json != null && !"".equals(json)) {
			Type type = new TypeToken<Map<String, ApiFinalResponse<UserDto>>>() {
			}.getType();
			Map<String, ApiFinalResponse<UserDto>> retMap = JsonUtil.jsonToObject(json, type);
			if (retMap != null && retMap.get(ApiMethodEnum.USER_GETSIMPLEPROFILE.getCode()) != null) {
				userDto = retMap.get(ApiMethodEnum.USER_GETSIMPLEPROFILE.getCode()).getResults();
			}
		}
		return userDto;
	}

}
